package com.test.base.api;

import com.alibaba.fastjson.JSONObject;
import com.test.base.dao.NideshopUserDao;
import com.test.base.entity.NideshopUser;
import com.test.base.utils.CusAccessObjectUtil;
import com.test.base.utils.TokenUtil;
import com.test.base.vo.api.*;
import com.test.base.vo.common.ResultData;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("api/auth")
public class AuthApi {
    private Logger logger = LoggerFactory.getLogger(AuthApi.class);
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private NideshopUserDao nideshopUserDao;

    @ApiOperation(value = "WXLogin", notes = "")
    @RequestMapping(value = "/loginByWeixin", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParam(name = "reqObject", value = "WxLogin info", paramType = "body", required = true, dataType = "WxCodeInfoVo")
    public ResultData loginByWeixin(HttpServletRequest request, @RequestBody WxCodeInfoVo reqObject) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={jscode}&grant_type=authorization_code";
        WxUserInfoVo fullUserInfo = reqObject.getUserInfo();
        WxUserInfoEtxVo userInfo = fullUserInfo.getUserInfo();
        String value = restTemplate.getForObject(url, String.class, "wxdd86082e083bef94", "85a15225ef4dbe8ba04456af4118fd5d", reqObject.getCode());
        WxInfoResult sessionData = JSONObject.parseObject(value, WxInfoResult.class);
        logger.info("wechat get info:{}", sessionData.toString());
        if (StringUtils.isEmpty(sessionData.getOpenid())) {
            return ResultData.fail("登录失败");
        }
        String dc = DigestUtils.sha1Hex(fullUserInfo.getRawData() + sessionData.getSession_key());
        logger.info("sha1 decode:{}", dc);
        if (!fullUserInfo.getSignature().equals(dc)) {
            return ResultData.fail("登录失败");
        }
        NideshopUser getByOpenId = new NideshopUser();
        getByOpenId.setWeixinOpenid(sessionData.getOpenid());
        NideshopUser user = nideshopUserDao.selectNideshopUserByObj(getByOpenId);
        String ip = CusAccessObjectUtil.getIpAddress(request);
        Long time =  new Date().getTime()/1000;
        if (user == null) {
            NideshopUser addUser = new NideshopUser();
            addUser.setUsername("微信用户" + UUID.randomUUID().toString());
            addUser.setPassword(sessionData.getOpenid());
            addUser.setRegisterTime(time);
            addUser.setRegisterIp(ip);
            addUser.setLastLoginTime(time);
            addUser.setLastLoginIp(ip);
            addUser.setWeixinOpenid(sessionData.getOpenid());
            addUser.setAvatar(userInfo.getAvatarUrl());
            addUser.setGender(userInfo.getGender()); // 性别 0：未知、1：男、2：女
            addUser.setNickname(userInfo.getNickName());
            nideshopUserDao.insertNonEmptyNideshopUser(addUser);
            user = addUser;
        } else {
            NideshopUser updateUser = new NideshopUser();
            updateUser.setId(user.getId());
            updateUser.setLastLoginTime(time);
            updateUser.setLastLoginIp(ip);
            nideshopUserDao.updateNonEmptyNideshopUserById(updateUser);
        }
        sessionData.setUserId(user.getId());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND,Integer.parseInt(sessionData.getExpires_in()));
        String sessionString = JSONObject.toJSONString(sessionData);
        String sessionKey = TokenUtil.create(sessionString,calendar.getTime());
        if (sessionKey.isEmpty()) {
            return ResultData.fail("登录失败");
        }
        ApiLoginResultVo loginResult = new ApiLoginResultVo();
        loginResult.setToken(sessionKey);
        loginResult.setUserInfo(user);
        return ResultData.success(loginResult);
    }
}
